package com.code.refactoring.ut_study.spring;

import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc;
import org.springframework.boot.test.autoconfigure.web.servlet.WebMvcTest;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.boot.test.mock.mockito.SpyBean;
import org.springframework.http.MediaType;
import org.springframework.test.context.ActiveProfiles;
import org.springframework.test.context.junit4.SpringRunner;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.request.MockMvcRequestBuilders;
import org.springframework.test.web.servlet.result.MockMvcResultHandlers;
import org.springframework.test.web.servlet.result.MockMvcResultMatchers;

import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.anyString;
import static org.mockito.Mockito.doNothing;
import static org.mockito.Mockito.doReturn;

@SpringBootTest
@RunWith(SpringRunner.class)
// @WebMvcTest(MockController.class) // 保证RequestMap可以被正确找到
@AutoConfigureMockMvc // 需要同时加上这2个注解，否则mockMvc会为null
@ActiveProfiles("dev")
public class MockControllerTest2 {

    // 使用这个注解，得加载spring容器，需要把 @SpringBootTest 带上
    @SpyBean
    private MockService mockService;

    @Autowired
    private MockMvc mockMvc;

    @Test
    public void funTest2() throws Exception {

        doReturn("wangxi mock 11111").when(mockService).findById(1L);
        // doNothing().when(mockService).save(anyString(), anyString());

        mockMvc.perform(MockMvcRequestBuilders.get("/mock/demo/fun")
                // 发送端和接收端数据格式
                .contentType(MediaType.APPLICATION_JSON_UTF8)
                .accept(MediaType.APPLICATION_JSON_UTF8)
        )
                // 断言校验返回的code编码
                .andExpect(MockMvcResultMatchers.status().isOk())
                // 添加处理器打印返回结果
                .andDo(MockMvcResultHandlers.print());
    }
}
